const WebSocket = require('ws');
const fs = require('fs');
const https = require('https');
const path = require('path');

// 检查是否存在测试证书
const certDir = path.join(__dirname, 'test-certs');
const keyPath = path.join(certDir, 'server-key.pem');
const certPath = path.join(certDir, 'server-cert.pem');

let server;
let wss;

if (fs.existsSync(keyPath) && fs.existsSync(certPath)) {
    console.log('Starting HTTPS WebSocket server with SSL certificates...');
    
    // 创建HTTPS服务器
    const serverOptions = {
        key: fs.readFileSync(keyPath),
        cert: fs.readFileSync(certPath)
    };
    
    server = https.createServer(serverOptions);
    wss = new WebSocket.Server({ server });
    
    server.listen(8443, () => {
        console.log('🔒 WSS (Secure WebSocket) server listening on wss://localhost:8443');
        console.log('📁 Using certificates from test-certs/ directory');
        console.log('');
        console.log('⚠️  Note: This uses a self-signed certificate.');
        console.log('   In the extension, use test-certs/ca-cert.pem as the certificate file.');
        console.log('');
    });
} else {
    console.log('⚠️  SSL certificates not found. Starting regular WebSocket server...');
    console.log('   Run ./create-test-certs.sh to generate test certificates for WSS testing.');
    console.log('');
}

// 同时启动普通的WebSocket服务器
const regularWss = new WebSocket.Server({ port: 8080 });
console.log('🌐 WS (Regular WebSocket) server listening on ws://localhost:8080');

// 处理连接的函数
function handleConnection(ws, serverType) {
    console.log(`📱 New ${serverType} connection established`);
    
    // 发送欢迎消息
    ws.send(JSON.stringify({
        type: 'welcome',
        message: `Connected to ${serverType} echo server`,
        timestamp: new Date().toISOString(),
        server: serverType
    }));
    
    // 处理消息
    ws.on('message', (data) => {
        try {
            const message = data.toString();
            console.log(`📨 ${serverType} received:`, message);
            
            // 尝试解析为JSON
            let response;
            try {
                const parsed = JSON.parse(message);
                response = {
                    type: 'echo',
                    original: parsed,
                    timestamp: new Date().toISOString(),
                    server: serverType,
                    format: 'json'
                };
            } catch {
                response = {
                    type: 'echo',
                    original: message,
                    timestamp: new Date().toISOString(),
                    server: serverType,
                    format: 'text'
                };
            }
            
            // 回显消息
            ws.send(JSON.stringify(response));
        } catch (error) {
            console.error(`❌ ${serverType} error:`, error.message);
            ws.send(JSON.stringify({
                type: 'error',
                message: error.message,
                timestamp: new Date().toISOString(),
                server: serverType
            }));
        }
    });
    
    // 处理连接关闭
    ws.on('close', () => {
        console.log(`📴 ${serverType} connection closed`);
    });
    
    // 处理错误
    ws.on('error', (error) => {
        console.error(`❌ ${serverType} WebSocket error:`, error.message);
    });
}

// 为普通WebSocket设置处理
regularWss.on('connection', (ws) => {
    handleConnection(ws, 'WS');
});

// 为安全WebSocket设置处理（如果证书存在）
if (wss) {
    wss.on('connection', (ws) => {
        handleConnection(ws, 'WSS');
    });
}

console.log('');
console.log('🚀 WebSocket test servers are running!');
console.log('');
console.log('Test URLs:');
console.log('  WS:  ws://localhost:8080');
if (wss) {
    console.log('  WSS: wss://localhost:8443');
}
console.log('');
console.log('Press Ctrl+C to stop the servers');

// 优雅关闭
process.on('SIGINT', () => {
    console.log('\n🛑 Shutting down WebSocket servers...');
    regularWss.close();
    if (wss && server) {
        server.close();
    }
    process.exit(0);
});
